package actions;

import javax.ejb.EJB;
import java.util.*;

import entities.*;

import javax.ejb.Local;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import utils.*;
import beans.*;


public class MainGeneratorAction extends ActionSupport {

	private static final long serialVersionUID = 8L;
    private ArrayList<Item> recentLibAdds;
    private ArrayList<Item> recentBorrowed;
    
    public ArrayList<Item> getRecentBorrowed() {
		return recentBorrowed;
	}
	public void setRecentBorrowed(ArrayList<Item> recentBorrowed) {
		this.recentBorrowed = recentBorrowed;
	}
	public ArrayList<Item> getRecentLibAdds() {
		return recentLibAdds;
	}
	public void setRecentLibAdds(ArrayList<Item> recentLibAdds) {
		this.recentLibAdds = recentLibAdds;
	}
	public ArrayList<Item> getRecentLoans() {
		return recentLoans;
	}
	public void setRecentLoans(ArrayList<Item> recentLoans) {
		this.recentLoans = recentLoans;
	}
	private ArrayList<Item> recentLoans;
    
    
    @EJB
    private SearchManager searchMan=new SearchBean();
 
	public String execute() {
		Object userIdObj=ActionContext.getContext().getSession().get("userId");
		if(userIdObj==null){
			//take the user to the login page
			this.addActionError("You must login to view this page");
			return ERROR;
		}
		
		int userId=((Integer)userIdObj).intValue();
		
		//items recently added to the library
		recentLibAdds = searchMan.getItems(userId, null, null, 5);
		recentLoans = searchMan.getItems(userId, Item.loaned, null, 5);
		recentBorrowed=searchMan.getLoanedItems(userId,5);
		ArrayList<Item> recalled=searchMan.getItems(userId, "RECALLED", null, 5);
		if(recalled!=null)recentLoans.addAll(recalled);
		//this.addActionMessage("RecentLibAdded: " + recentLibAdds.size());
		Object err=ActionContext.getContext().getSession().get("error");
		if(err!=null){
			ActionContext.getContext().getSession().remove("error");
			this.addActionError(err.toString());
			return "prevError";
		}
		return SUCCESS;
	}

}